<html>
 <head>
  <meta charset="utf-8"/>
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"/>
  <title>
   主题：关于C#与R语言的求助  | 数螺 | NAUT IDEA
  </title>
  <link href="http://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" rel="stylesheet"/>
  <link href="http://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
  <style type="text/css">
   #xmain img {
                  max-width: 100%;
                  display: block;
                  margin-top: 10px;
                  margin-bottom: 10px;
                }

                #xmain p {
                    line-height:150%;
                    font-size: 16px;
                    margin-top: 20px;
                }

                #xmain h2 {
                    font-size: 24px;
                }

                #xmain h3 {
                    font-size: 20px;
                }

                #xmain h4 {
                    font-size: 18px;
                }


                .header {
	           background-color: #0099ff;
	           color: #ffffff;
	           margin-bottom: 20px;
	        }

	        .header p {
                  margin: 0px;
                  padding: 10px 0;
                  display: inline-block;  
                  vertical-align: middle;
                  font-size: 16px;
               }

               .header a {
                 color: white;
               }

              .header img {
                 height: 25px;
              }
  </style>
  <script src="http://cdn.bootcss.com/jquery/3.0.0/jquery.min.js">
  </script>
  <script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML" type="text/javascript">
   MathJax.Hub.Config({elements: ["bbpress-forums"]});
  </script>
  <script src="http://nautstatic-10007657.file.myqcloud.com/static/css/readability.min.js" type="text/javascript">
  </script>
  <script type="text/javascript">
   $(document).ready(function() {
                 var loc = document.location;
                 var uri = {
                  spec: "http://cos.name/cn/topic/103438/",
                  host: "http://cos.name",
                  prePath: "http://cos.name",
                  scheme: "http",
                  pathBase: "http://cos.name/"
                 };
    
                 var documentClone = document.cloneNode(true);
                 var article = new Readability(uri, documentClone).parse();
     
                 document.getElementById("xmain").innerHTML = article.content;
                });
  </script>
  <!-- 1466441012: Accept with keywords: (title(0.5):C#,R语言,主题,论坛, topn(0.133333333333):RSS订阅,软件应用,主页,帖子,测试通过,R语言,作者,会员,类库,用户名,Python,主站,上宫,大虾,python,电脑,论坛,程序包,密码,普通,返回值,环境变量,版主,开始菜单,新建,主题,总计,C#,按钮,讨论区).-->
 </head>
 <body class="topic bbpress single single-topic postid-103438 single-author sidebar" onload="">
  <div class="header">
   <div class="container">
    <div class="row">
     <div class="col-xs-6 col-sm-6 text-left">
      <a href="/databee">
       <img src="http://nautidea-10007657.cos.myqcloud.com/logo_white.png"/>
      </a>
      <a href="/databee">
       <p>
        数螺
       </p>
      </a>
     </div>
     <div class="hidden-xs col-sm-6 text-right">
      <p>
       致力于数据科学的推广和知识传播
      </p>
     </div>
    </div>
   </div>
  </div>
  <div class="container text-center">
   <h1>
    主题：关于C#与R语言的求助
   </h1>
  </div>
  <div class="container" id="xmain">
   <div class="hfeed site" id="page">
    <header class="site-header" id="masthead" role="banner">
     <div id="cos-logo">
      <a href="http://cos.name/cn">
       <img src="http://cos.name/cn/wp-content/themes/COS-forest/images/headers/cos-logo.png"/>
      </a>
     </div>
     <div class="navbar" id="navbar">
      <nav class="navigation main-navigation" id="site-navigation" role="navigation">
       <h3 class="menu-toggle">
        菜单
       </h3>
       <div class="menu-%e8%8f%9c%e5%8d%951-container">
        <ul class="nav-menu" id="menu-%e8%8f%9c%e5%8d%951">
         <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-407772" id="menu-item-407772">
          <a href="http://cos.name/cn/">
           论坛首页
          </a>
         </li>
         <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-407773" id="menu-item-407773">
          <a href="http://cos.name/cn/forums/">
           讨论区
          </a>
         </li>
         <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-407774" id="menu-item-407774">
          <a href="http://cos.name/cn/wp-login.php?action=register">
           注册
          </a>
         </li>
         <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-407819" id="menu-item-407819">
          <a href="http://cos.name/">
           主站
          </a>
         </li>
        </ul>
       </div>
      </nav>
      <!-- #site-navigation -->
     </div>
     <!-- #navbar -->
    </header>
    <!-- #masthead -->
    <div class="site-main" id="main">
     <div class="content-area" id="primary">
      <div class="site-content" id="content" role="main">
       <article class="post-103438 topic type-topic status-publish hentry" id="post-103438">
        <header class="entry-header">
         <h1 class="entry-title">
          关于C#与R语言的求助
         </h1>
        </header>
        <!-- .entry-header -->
        <div class="entry-content">
         <div id="bbpress-forums">
          <div class="bbp-breadcrumb">
           <p>
            <a class="bbp-breadcrumb-home" href="http://cos.name/cn/">
             COS论坛 | 统计之都
            </a>
            <span class="bbp-breadcrumb-sep">
             ›
            </span>
            <a class="bbp-breadcrumb-root" href="http://cos.name/cn/forums/">
             讨论区
            </a>
            <span class="bbp-breadcrumb-sep">
             ›
            </span>
            <a class="bbp-breadcrumb-forum" href="http://cos.name/cn/forum/software/">
             软件应用
            </a>
            <span class="bbp-breadcrumb-sep">
             ›
            </span>
            <a class="bbp-breadcrumb-forum" href="http://cos.name/cn/forum/software/r-language/">
             S-Plus &amp; R语言
            </a>
            <span class="bbp-breadcrumb-sep">
             ›
            </span>
            <span class="bbp-breadcrumb-current">
             关于C#与R语言的求助
            </span>
           </p>
          </div>
          <div class="bbp-template-notice info">
           <p class="bbp-topic-description">
            该主题包含 6 条回复，3个帖子，最后由
            <a class="bbp-author-avatar" href="http://cos.name/cn/profile/368205/" rel="nofollow" title="查看lincpa的档案">
             <img src="http://sdn.geekzu.org/avatar/498a47a5dba4347e539ca84572533720?s=14&amp;d=monsterid&amp;r=g"/>
            </a>
            <a class="bbp-author-name" href="http://cos.name/cn/profile/368205/" rel="nofollow" title="查看lincpa的档案">
             lincpa
            </a>
            在
            <a href="http://cos.name/cn/topic/103438/#post-314046" title="回复：关于C#与R语言的求助">
             5 年, 4 月 之前
            </a>
            更新。
           </p>
          </div>
          <div class="bbp-pagination">
           <div class="bbp-pagination-count">
            查看 7 个帖子 - 1 到 7（总计 7 个）
           </div>
           <div class="bbp-pagination-links">
           </div>
          </div>
          <ul class="forums bbp-replies" id="topic-103438-replies">
           <li class="bbp-header">
            <div class="bbp-reply-author">
             作者
            </div>
            <!-- .bbp-reply-author -->
            <div class="bbp-reply-content">
             帖子
            </div>
            <!-- .bbp-reply-content -->
           </li>
           <!-- .bbp-header -->
           <li class="bbp-body">
            <div class="bbp-reply-header" id="post-103438">
             <div class="bbp-meta">
              <span class="bbp-reply-post-date">
               2011年1月17日 上午9:48
              </span>
              <a class="bbp-reply-permalink" href="http://cos.name/cn/topic/103438/#post-103438">
               1 楼
              </a>
              <span class="bbp-admin-links">
              </span>
             </div>
             <!-- .bbp-meta -->
            </div>
            <!-- #post-103438 -->
            <div class="odd bbp-parent-forum-999 bbp-parent-topic-103438 bbp-reply-position-1 user-id-369166 topic-author post-103438 topic type-topic status-publish hentry">
             <div class="bbp-reply-author">
              <a class="bbp-author-avatar" href="http://cos.name/cn/profile/369166/" rel="nofollow" title="查看yquan的档案">
               <img src="http://sdn.geekzu.org/avatar/dd57737381eb5aed04361397500d2c06?s=80&amp;d=monsterid&amp;r=g"/>
              </a>
              <br/>
              <a class="bbp-author-name" href="http://cos.name/cn/profile/369166/" rel="nofollow" title="查看yquan的档案">
               yquan
              </a>
              <br/>
              <div class="bbp-author-role">
               普通会员
              </div>
             </div>
             <!-- .bbp-reply-author -->
             <div class="bbp-reply-content">
              <p>
               要做一个使用C#开发的windows程序，其中要对数据做一些统计，于是开始关注R语言。查到网友都只是使用R(D)COM来连接二者，除此之外，有别的办法吗？还请大虾们不吝赐教。
               <br/>
               另外，我尝试使用R(D)COM，却一直连接不上，查遍了资料也没有解决问题：安装R，安装rscproxy程序包，安装R(D)COM…总之还是失败。不知道原因在哪。
               <br/>
               请了解的指点下！先谢谢！[s:14]
              </p>
             </div>
             <!-- .bbp-reply-content -->
            </div>
            <!-- .reply -->
            <div class="bbp-reply-header" id="post-313788">
             <div class="bbp-meta">
              <span class="bbp-reply-post-date">
               2011年1月24日 上午9:36
              </span>
              <a class="bbp-reply-permalink" href="http://cos.name/cn/topic/103438/#post-313788">
               2 楼
              </a>
              <span class="bbp-admin-links">
              </span>
             </div>
             <!-- .bbp-meta -->
            </div>
            <!-- #post-313788 -->
            <div class="even bbp-parent-forum-999 bbp-parent-topic-103438 bbp-reply-position-2 user-id-336 post-313788 reply type-reply status-publish hentry">
             <div class="bbp-reply-author">
              <a class="bbp-author-avatar" href="http://cos.name/cn/profile/336/" rel="nofollow" title="查看刘思喆的档案">
               <img src="http://sdn.geekzu.org/avatar/6ca0529d22d1bf25a1e5cee3af3456f9?s=80&amp;d=monsterid&amp;r=g"/>
              </a>
              <br/>
              <a class="bbp-author-name" href="http://cos.name/cn/profile/336/" rel="nofollow" title="查看刘思喆的档案">
               刘思喆
              </a>
              <br/>
              <div class="bbp-author-role">
               版主
              </div>
             </div>
             <!-- .bbp-reply-author -->
             <div class="bbp-reply-content">
              <p>
               R会议上宫雨老师有一篇演讲材料可以参考一下
               <br/>
               还有李舰的，忘记哪年的了
              </p>
             </div>
             <!-- .bbp-reply-content -->
            </div>
            <!-- .reply -->
            <div class="bbp-reply-header" id="post-314024">
             <div class="bbp-meta">
              <span class="bbp-reply-post-date">
               2011年1月31日 下午12:11
              </span>
              <a class="bbp-reply-permalink" href="http://cos.name/cn/topic/103438/#post-314024">
               3 楼
              </a>
              <span class="bbp-admin-links">
              </span>
             </div>
             <!-- .bbp-meta -->
            </div>
            <!-- #post-314024 -->
            <div class="odd bbp-parent-forum-999 bbp-parent-topic-103438 bbp-reply-position-3 user-id-368205 post-314024 reply type-reply status-publish hentry">
             <div class="bbp-reply-author">
              <a class="bbp-author-avatar" href="http://cos.name/cn/profile/368205/" rel="nofollow" title="查看lincpa的档案">
               <img src="http://sdn.geekzu.org/avatar/498a47a5dba4347e539ca84572533720?s=80&amp;d=monsterid&amp;r=g"/>
              </a>
              <br/>
              <a class="bbp-author-name" href="http://cos.name/cn/profile/368205/" rel="nofollow" title="查看lincpa的档案">
               lincpa
              </a>
              <br/>
              <div class="bbp-author-role">
               普通会员
              </div>
             </div>
             <!-- .bbp-reply-author -->
             <div class="bbp-reply-content">
              <p>
               The R Statistical Language and C#.NET: Foundations
               <br/>
               By Jeff B. Cromwell | 14 May 2008
               <br/>
               Use the R Language in C#.NET applications.
              </p>
              <p>
               Introduction
               <br/>
               Over a decade ago, my colleagues and I wrote two books on using different tests for examining the assumptions of time series analysis in both the univariate and multivariate contexts. Back then, the programs to conduct these tests were a mixture of Basic, C, and the use of some batch programs in commercial packages such as RATS, SHAZAM, and TSP.
              </p>
              <p>
               Cromwell, J.B., M.J. Hannan, W.C. Labys, and M. Terraza. 1994. Multivariate Testing for Time Series Models. New York: Sage Publication.
               <br/>
               Cromwell, J.B., W.C. Labys and M. Terraza. 1994. Univariate Testing for Time Series Models. New York: Sage Publications.
               <br/>
               Today, other packages such as SAS, SPSS, Ox, Matlab, and S-Plus can be used to do similar work. However, a favorite open source statistical package of mine was and continues to be developed by researchers at Carnegie Mellon University, known as the statistical language R. The R language can be downloaded from here. Once installed, go to the Package menu in R and select all the packages, and hit Enter. This will install all the libraries so that the baseline Splus and R are the same. R uses the S language, and Fox (2002) and Farnsworth (2006) provide excellent references for doing the time series analysis mentioned in my two books. In a series of papers, I plan to demonstrate using R and C#.NET for a wide variety of statistical and analytical applications that can be built in a typical 3-4 hours of work.
              </p>
              <p>
               Background
               <br/>
               Besides using the GUI shown in Figure 1, I wanted to be able to use R as an intelligence component in my research applications. At the University, publication for applied work is always going to need the latest statistical techniques, and for this, a programming language. Because of my background in both .NET and Java, I chose to use C#.NET for the interface language to build these middleware pieces. I downloaded Microsoft Visual C# 2008 Express Edition, and wanted to attach the references for the R .NET component to begin the work of this middleware application. Since there was not a .NET component bundled with R, I used the R-(D) COM interface for the automation.
              </p>
              <p>
               Figure 1. The GUI interface to R
              </p>
              <p>
               R in .NET – The R(D) COM interface
               <br/>
               The R-(D) COM interface is a COM server that can connect to applications such as Microsoft Excel to take advantage of the statistical techniques that are constantly being added to the R releases. In addition, there are ActiveX controls that can be included in the application. Thus, data can be transferred in and out of R, and Visual Basic, C#, and Perl can serve as COM clients that enable one to use R as a computational engine that also can render graphics. The COM server can be downloaded and installed by following these steps:
              </p>
              <p>
               Go to cran.r-project.org
               <br/>
               Choose “Other” item from the Software menu
               <br/>
               Choose R-(D) COM Interface (for Windows)
               <br/>
               Choose RServer250.exe
               <br/>
               Install the application
               <br/>
               Once installed, you can add the following COM references to your C#.NET project, as well as these namespaces to your class:
              </p>
              <p>
               Collapse | Copy Code
               <br/>
               //
               <br/>
               // COM References
               <br/>
               //
               <br/>
               using STATCONNECTORCLNTLib;
               <br/>
               using StatConnectorCommonLib;
               <br/>
               using STATCONNECTORSRVLib;Each of these type libraries uses the .NET interoperability feature for operation. Use the using statements in the code.
              </p>
              <p>
               The code to use the .NET component as an interface to R is quite simple, and has only a few statements that can execute data in, process it, and then extract it. For example, to generate twenty random normal numbers, one uses:
              </p>
              <p>
               Collapse | Copy Code
               <br/>
               object o1;
               <br/>
               int n=20;
               <br/>
               StatConnector sc1 = new StatConnectorSRVLib.StatConnectorClass();
               <br/>
               Sc1.Init(“R”);
               <br/>
               Sc1.SetSymbol(“n1”,n);
               <br/>
               Sc1.Evaluate(“x1&lt;-rnorm(n1)”);
               <br/>
               O1=sc1.GetSymbol(“x1”);
               <br/>
               Xrnd=(double) o1;Once we instantiate the class with sc1 and initialize R, we can then generate data with a declaration of n1 as the object type in R and n to be the integer type – the number of normal random numbers we want to generate. The SetSymbol() function is used cast the C# type to an R type. Then, we can use the GetSymbol() function to get the variable, and then cast it to an object for processing. For more understanding of the R data types, examine the help documentation that comes with R.
              </p>
              <p>
               Importing the data
               <br/>
               While we can generate data within R, it would also be instructive to import data into R. For example, you can read data from more than one data format. The most common format is a text file, with data separated into columns, with a header for each column. I created a list of numbers, one in each line, in Notepad, to import into R. This chooses the file through a dialog.
              </p>
              <p>
               Collapse | Copy Code
               <br/>
               &gt;mydata = read.table( file.chooseO, skip = 1 ) The file.choose() function provides the dialog to choose the text file, and the skip=1 parameter says to skip the first line for the Header value. The R variable is mydata and the name of values is V1. To see the data:
              </p>
              <p>
               Collapse | Copy Code
               <br/>
               &gt;mydataIn the dialog window, the values are shown for the variable V1. Suppose, I would like to read in these data values into a variable that represents a yearly time series that represents a stock’s values:
              </p>
              <p>
               Collapse | Copy Code
               <br/>
               &gt;zl &lt;-ts(mydata,start=c(1992,8), 1)
               <br/>
               &gt;plot(zl) I can use the following ts() function that starts with the year 1999, with the frequency being yearly. Of course, I can plot these numbers to verify as well as look at the values of z1. Now that we can do this in the R application, how do we do this in C#.NET and not use the R Windows interface? Importing can be problematic when taking the expressions directly over to C#, so I use a traditional text file or database work to populate the variables and then use the SetSymbol() function to import the values into R and then do transformations. However, we can use the EvaluateNoReturn() function to read in the data with:
              </p>
              <p>
               Collapse | Copy Code
               <br/>
               Sc1.EvaluateNoReturn(“m1=read.table(file.choose())”);The difference between Evaluate() and EvaluateNoReturn() is that the former returns the reference to an object, which is necessary when casting and extracting data from the R environment. As a rule, this is how I prototype and test my statistical components, write them for execution in the R Windows interface, save them to text, and then read the file one line at a time with one evaluate function. Then, you can modify the text files, or combine multiple text files for statistical processing. This provides for a very creative modeling and analytical environment. Besides the computational aspects mentioned, one can also render graphics through the using statement:
              </p>
              <p>
               Collapse | Copy Code
               <br/>
               using STATCONNECTORCLNTLib; The R graphics device
               <br/>
               The code to generate a histogram plot of twenty normal random variables is provided by:
              </p>
              <p>
               Collapse | Copy Code
               <br/>
               StatConnector test1= new STATCONNECTORSRVLib.StatConnectorClass();
               <br/>
               test1.Init(“R”);
               <br/>
               test1.Evaluate(“x&lt;-rnorm(20)”);
               <br/>
               test1.EvaluateNoReturn(“hist(x)”);// The R graphics device populates its own dialog window with the histogram results. This nice feature automatically provides additional graphical resources and libraries for doing 2D and 3D charting. The dialog window permits the ability to save in a variety of graphics format, print, and save to the clipboard. Furthermore, you can examine the history and resize options. Again, refer to the R documentation for the necessary expressions and packages.
              </p>
              <p>
               Figure 2. Histogram of normal random numbers
              </p>
              <p>
               As one can see, an understanding of the R language and the use of the bundled packages permit the opportunity to build a business forecasting or analytical application quickly. Download some stock data from Yahoo!, and throw it into SQL Express and use LINQ for the OEM, and reference the R COM component, download some packages, and forecast some stocks using the latest methods in time series analysis. This is the subject of Part II of the series.
              </p>
              <p>
               Conclusion
               <br/>
               Using the open source R statistical language is a good way to incorporate the latest statistical research into your business intelligence prototypes and applications, as it presents a low cost alternative for the development and implementation of statistical algorithms for predictive analytics not available in standard commercial packages. I have used R in this fashion for doing wavelet analysis for price analytics, watershed modeling for acid mine drainage, and for stochastic volatility modeling of stocks using Bayesian Markov Chain Monte Carlo (MCMC) techniques. In future articles, I plan to show how to build these types of applications in 3-4 hours of programming work.
              </p>
              <p>
               References
               <br/>
               Farnsworth, G.V. (2006), Econometrics in R.
               <br/>
               Fox, J. (2002), An R and S-Plus Companion to Applied Regression, Thousand Oaks, CA: Sage Publications.
               <br/>
               License
               <br/>
               This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
              </p>
              <p>
               About the Author
               <br/>
               Jeff B. Cromwell
              </p>
              <p>
               Software Developer (Senior)
              </p>
              <p>
               United States
              </p>
              <p>
               Member
               <br/>
               Dr. Jeff B. Cromwell is a software consultant and lives in Harrisburg, PA. He has held teaching and research positions at West Virginia University, California University of Pennsylvania, Edinboro University of Pennsylvania and given time series workshops at the University of Michigan. His clients include State Farm Insurance, US Postal Service, General American, Edward Jones, GeoDecisions, I3, Ameren UE, and The Pennsylvania Lottery. His speciality is in the development of space-time analytical systems using arcGIS,.NET and SQL Server based architectures.
              </p>
              <p>
               Article TopSign Up to vote for this article
              </p>
              <p>
               Add a reason or comment to your vote: x
              </p>
              <p>
               Comments and Discussions
               <br/>
               You must Sign In to use this message board.
               <br/>
               FAQ
               <br/>
               Noise Tolerance Very HighHighMediumLowVery Low  Layout NormalExpand Posts onlyExpand Posts &amp; RepliesThread ViewNo JavascriptNo JS + Preview  Per page 102550
              </p>
              <p>
               Msgs 1 to 10 of 31 (Total in Forum: 31) (Refresh) FirstPrevNext
              </p>
              <p>
               Exception from HRESULT: 0x80040013  caoboidibo 19:07 4 Oct ’10
              </p>
              <p>
               I followed yr article and run the code, but i got this error
               <u>
                Exception from HRESULT: 0x80040013
               </u>
               on the line
               <u>
                Sc1.Init(“R”);
               </u>
              </p>
              <p>
               Can anyone help?
              </p>
              <p>
               Sign In·View Thread·PermaLink
              </p>
              <p>
               Re: Exception from HRESULT: 0x80040013  maestroagressor 5:40 5 Oct ’10
              </p>
              <p>
               Do you have rscproxy installed as package ?
              </p>
              <p>
               Sign In·View Thread·PermaLink
              </p>
              <p>
               My vote of 5  Gmust 11:15 14 Sep ’10
              </p>
              <p>
               Great tool!
              </p>
              <p>
               Sign In·View Thread·PermaLink
              </p>
              <p>
               R program  senthilnathan thandapani 19:25 27 Jun ’10
              </p>
              <p>
               Hi,
              </p>
              <p>
               I am unable to find RServer250.exe in cran.r-project.org. can anyone help me please?
              </p>
              <p>
               Sign In·View Thread·PermaLink
              </p>
              <p>
               LM and GLM function  Member 3069551 10:24 1 May ’10
              </p>
              <p>
               Hello, I installed all the tools that is necesary to run R form C#, but when I try to run this code:
              </p>
              <p>
               StatConnector sc1 = new STATCONNECTORSRVLib.StatConnectorClass();
               <br/>
               try {
               <br/>
               sc1.Init(“R”);
               <br/>
               sc1.Evaluate(“a &lt;- c(0,1,0,1,0,1,0,1,0,1)”);
               <br/>
               sc1.Evaluate(“b = c(1,2,3,4,5,6,7,8,9,10)”);
              </p>
              <p>
               object a = sc1.GetSymbol(“a”);
               <br/>
               object b = sc1.GetSymbol(“b”);
              </p>
              <p>
               //sc1.Evaluate(“modelo = glm(a ~ b, family=’binomial’)”);
               <br/>
               sc1.Evaluate(“modelo = lm(a ~ b)”);
               <br/>
               }
               <br/>
               catch (Exception ex)
               <br/>
               {
               <br/>
               Console.WriteLine(ex.Message);
               <br/>
               Console.WriteLine(sc1.GetErrorId() + ” – ” + sc1.GetErrorText());
               <br/>
               }
              </p>
              <p>
               The code throws this exception: “There is no connection for this connection ID (Exception from HRESULT: 0x80040004 (OLE_E_NOCONNECTION))”.
               <br/>
               Anyone know why this happend?
              </p>
              <p>
               Thanks.
              </p>
              <p>
               Sign In·View Thread·PermaLink 1.00/5 (1 vote)
              </p>
              <p>
               Re: LM and GLM function  michaelnye 15:41 26 May ’10
              </p>
              <p>
               The solution is this for those wondering about this:
              </p>
              <p>
               <a href="http://mailman.csd.univie.ac.at/pipermail/rcom-l/2009-August/003142.html%5B" rel="nofollow">
                http://mailman.csd.univie.ac.at/pipermail/rcom-l/2009-August/003142.html%5B
               </a>
               ^]
              </p>
              <p>
               You have to call the lm() function using EvaluateNoReturn then pick out the bits of information you wish to read.
              </p>
              <p>
               Sign In·View Thread·PermaLink
              </p>
              <p>
               Re: LM and GLM function  Member 4772428 2:55 13 Aug ’10
              </p>
              <p>
               I posted a couple of blog posts on C# and R interfacing which you might find interesting …
              </p>
              <p>
               <a href="http://vvella.blogspot.com/2010/08/integrate-c-net-and-r-taking-best-of.html%5B" rel="nofollow">
                http://vvella.blogspot.com/2010/08/integrate-c-net-and-r-taking-best-of.html%5B
               </a>
               ^]
              </p>
              <p>
               Sign In·View Thread·PermaLink
              </p>
              <p>
               Embed R plot in C# windows form  vats85 11:01 12 Jun ’09
              </p>
              <p>
               I am trying to embed R plots in a visual C# windows form, so that I can have some buttons, and by clicking them, I can plot the chart on that window itself. Do you guys think this is possible to do?
              </p>
              <p>
               Sign In·View Thread·PermaLink 1.50/5 (2 votes)
              </p>
              <p>
               Re: Embed R plot in C# windows form  hhhaui 3:13 17 Jul ’09
              </p>
              <p>
               i have the same problem!~
              </p>
              <p>
               Sign In·View Thread·PermaLink
              </p>
              <p>
               Re: Embed R plot in C# windows form  retool 9:07 21 Nov ’09
              </p>
              <p>
               If you can tolerate an indirect method you might try creating a pdf or jpeg then pulling that into the C# form. If you want to interact with the plot (using identify etc.) then you are probably stuck with directing the user to the window that R pops up.
              </p>
              <p>
               Sign In·View Thread·PermaLink
              </p>
             </div>
             <!-- .bbp-reply-content -->
            </div>
            <!-- .reply -->
            <div class="bbp-reply-header" id="post-314025">
             <div class="bbp-meta">
              <span class="bbp-reply-post-date">
               2011年1月31日 下午12:13
              </span>
              <a class="bbp-reply-permalink" href="http://cos.name/cn/topic/103438/#post-314025">
               4 楼
              </a>
              <span class="bbp-admin-links">
              </span>
             </div>
             <!-- .bbp-meta -->
            </div>
            <!-- #post-314025 -->
            <div class="even bbp-parent-forum-999 bbp-parent-topic-103438 bbp-reply-position-4 user-id-368205 post-314025 reply type-reply status-publish hentry">
             <div class="bbp-reply-author">
              <a class="bbp-author-avatar" href="http://cos.name/cn/profile/368205/" rel="nofollow" title="查看lincpa的档案">
               <img src="http://sdn.geekzu.org/avatar/498a47a5dba4347e539ca84572533720?s=80&amp;d=monsterid&amp;r=g"/>
              </a>
              <br/>
              <a class="bbp-author-name" href="http://cos.name/cn/profile/368205/" rel="nofollow" title="查看lincpa的档案">
               lincpa
              </a>
              <br/>
              <div class="bbp-author-role">
               普通会员
              </div>
             </div>
             <!-- .bbp-reply-author -->
             <div class="bbp-reply-content">
              <p>
               S and COM via Objects
              </p>
              <p>
               Duncan Temple Lang
              </p>
              <p>
               Statistic and Data Mining Resarch, Bell Labs
               <br/>
               Abstract
              </p>
              <p>
               This document describes the philosophy that motivates the use the RDCOM packages and contrasts that with other approaches. Specifically, it describes the need for being able to expose S functionality and values as regular COM objects rather than simply expose the R command interpreter.
               <br/>
               The traditional approach
              </p>
              <p>
               Inter-system interfaces are very attractive. They allow programmers in one language or system to readily use code in another language or system with very little overhead. They do not have to translate the original code into their own language. Instead, they only have to install the inter-system mechanism and invoke the relevant code. There are a lot of these inter-system interfaces available now, and this is also true for S, and specifically R. We can call Java, Perl, Python, Octave, XLisp, Objective-C, (D)COM from S and, importantly, vice-versa.
               <br/>
               When people think of making S available to other programming languages, they typically suggest that one should be able to send S commands from these other languages. S will evaluate them and one can generate plots or write to files, and in some cases even get back the results from evaluating the command. As an example, one might write some Visual Basic code to generate some random numbers in R.
               <br/>
               Dim x As Object
               <br/>
               R = CreateObject(“R.Evaluator”)
               <br/>
               x = R.evaluate(“rnorm(10)”)
               <br/>
               So far this is quite easy. The array is sent back to the Visual Basic function from R and the values are immediately available.
              </p>
              <p>
               There are four ways in which this style of computing can be limiting.
              </p>
              <p>
               &lt;java:class&gt;java.awt.ActionListener&lt;/java:class&gt;IConnectionPoint
              </p>
              <p>
               The programmer must know the S language and its syntax to be able to construct commands. This defeats the purpose of programming in this other language. Instead of having a single programming language to deal with and debug, the programmer must switch between two and deal explicitly with both. While it is beneficial to have the additional functionality, the interface places the burden on each user of the interface, not the interface itself. Instead, we want the programmer to be able to think of the additional functionality in the usual terms of her existing and familiar programming language. So in Visual Basic, for example, we want S functions to appear as if they are VB routines.
               <br/>
               In addition to having to know the S language, the programmer in the other system must also construct these commands as part of their code. They must use data that is local to their program to parameterize the S commands to get the desired behavior and they must do this by pasting together elemens of the command as strings. For example, suppose in our example above that we wanted to generate a sample of size n rather than the fixed and constant value 10. n is a variable in the local program, say in Java. In this case, we have to construct the command as a string something like &lt;java:code&gt; cmd = “rnorm(” + n + “)” &lt;/java:code&gt; If we have three arguments to the function (e.g. the mean and standard deviation), we would do something &lt;java:code&gt; cmd = “rnorm(” + n + “, ” + mean + “, ” + sd + )” &lt;/java:code&gt; This starts to get more complex to type and match the commas, etc. Essentially, we are writing one language in another and this demanding but tedious. It is conceptually quite simple, as is a lot of programming, but the opportunities to make a mistake abound. Unbalanced parentheses, missing commas, etc. are common. If a local function deals with an arbitrary number of arguments and puts these into the command, it must explicitly loop, check whether we put a comma or are we at the final argument, etc.
               <br/>
               A far more important and technical problem arises in how we represent data from the local system in the command as a string. For example, suppose we have a &lt;java:class&gt;javax.swing.Window&lt;/java:class&gt; in Java and need to pass it to R. Clearly, there is no fool-proof way to put this into the command represented as a string. One can ask what good it would do R to have access to this. Firstly, if R can call Java methods, then the R code might invoke a method on the Window object as part of its actions. More straightforwardly, R might simply pass the Window object to another Java method. If we cannot pass the Window object to the R function, we would have to have written the original Java code to put the object into a global variable and have the other Java method look there. So we might use global variables, rewrite the original code, or alternatively implement some scheme for passing an identifier to R which can be resolved back in Java by the relevant Java methods. All of this greatly detracts from the use of the inter-system interfaces. It limits the utility of the interface to computations that involve data that can be represented as a string, or it involves rewriting the existing code or using some ad hoc, homespun techniques to manage the communication.
               <br/>
               To be useful, we must be able to pass objects between the systems. And for those objects that have no corresponding meaning in the remote system, we must be able to pass a reference to the original object.
              </p>
              <p>
               One of the major drawbacks of the interface that only allows commands to be evaluated is how we return complex, i.e. non-primitive, values. For example, suppose we use R to fit a linear model via the lm function. Again, we have an issue of how we can pass the data to R. We can represent it explicitly in the command something like
               <br/>
               R.evaluate(“lm(y ~ ., data = data.frame(y = c(1.2, 3.2,…), x1 =  c(…), x2 = c(…)))”)
               <br/>
               Alternatively, we could create the dataset in R ahead of time using several commands
              </p>
              <p>
               R.evaluate(“myData &lt;&lt;- data.frame()”)
               <br/>
               R.evaluate(“myData$y &lt;&lt;- c(1.2, 3.2,…)”)
               <br/>
               R.evaluate(“myData$x1 &lt;&lt;-  c(…)”)
              </p>
              <p>
               and so on. Which is more convenient depends on the context. But note that we now have two scopes or evaluation contexts to worry about: R’s and the local one. The data lives in local variables and we are explicitly creating R variables in the R session. We have to be very careful to choose names that don’t overwrite existing data used in other routines that manage data in this same way. Again, we are using global variables, albeit in a different system, and have sacrificied modularity and maintainability in our code.
               <br/>
               With this issue aside, how do we return the result of the linear model fit. Clearly there is no obvious way to bring it back with all its meaning to the original system. In some of the inter-system interfaces, we know the two languages involved, e.g. R and Perl. In that case, we can use a default approach which is to copy the elements of an R list, e.g. the lm object, to a Perl object with the same elements. In this way, we do a deep recursive copy. This will get the data contents across but not necessarily the semantics of the object.
              </p>
              <p>
               In the case of COM, we don’t have any information about the client to which we are returning the value. In this case, we must keep the data on the server in which it was created and present it to the client in a suitable form. In other words, we must create a COM object that provides the client with access to the values. To do this in S, we obviously must have a mechanism to create a regulr COM object which can be used to access the elements of the object and even call methods on it. Without this facility, the client must be careful to ensure that non-basic values are returned. It must do this by assinging the results to R’s global environment/workspace and always returning a primitive value. In the case of the lm above
              </p>
              <p>
               In some cases, we explicitly do not want to have a copy of it returned to the original system. Instead, we must have a reference to the object so that it can be updated in subsequent calls and shared across these calls.
              </p>
              <p>
               How do we do this? There must be a mechanism for creating a reference to an S object and returning that reference as an value in the non-S system. If we do this, the programmer in, say, Python can then ask for the different elements in the S object, or invoke methods or functions on that object. This model will allow us to perform all types of computations and in a vary natural way. Instead of sending S language commands to R which refer to variables in its global namespace created as a result of previous expression, we can invoke functions/methods on objects as we do on local objects in the non-S language. In this way, the programmer doesn’t have to know the S syntax but can use its functionality directly as if it were local. And importantly, the computations are not limited to simple data types such as primitive values and arrays of primitive values.
              </p>
              <p>
               S-Plus’s COM interface
              </p>
              <p>
               S-Plus provides a mechanism for exposing S functions as COM objects. The model (see &lt;cite&gt;&lt;/cite&gt;) for the client is that the caller populates the collection of relevant arguments by assigning values to argument names (and specifying the types) and then calls the Run. This returns a status value indicating whether the call was successful or not. If it was, the result is available in the property ReturnValue. This is cumbersome way of programming. For example, if we want to call the rnorm with the sample size and the standard deviation, we do something like the following (untested) in Perl:
              </p>
              <p>
               $f = Win32::OLE-&gt;new(“S.rnorm”);
               <br/>
               $f-&gt;n = 100;
               <br/>
               $f-&gt;sd = 20;
               <br/>
               if($f-&gt;run()) {
               <br/>
               @x = @{$f-&gt;ReturnValue};
               <br/>
               }
              </p>
              <p>
               We always have to use the argument names. And getting the return value is separate from the act of invoking the function call. Perhaps one of the most problematic aspects of this model is that the COM object representing the function has state. We store the arguments in the object and call it separately. In most languages, function calls are atomic actions, but this is not the case here. This means that potentially two clients could be accessing the object at the same time and setting arguments and interfering with each other. We don’t even need two clients, just two calls, for this to happen. Suppose that a client was to use a random value from the Uniform distribution and the maximum value is to be chosen from another Uniform distribution. Imagine that we define a Python function for this:
               <br/>
               def getUniform(n, min = 0, max = 1)
               <br/>
               “Assume that runif is a global object that has been initialized as CreateObject(‘runif’)”
               <br/>
               runif.n = n;
               <br/>
               runif.max = getUniform(1, max = 20)
               <br/>
               runif.run();
               <br/>
               x = runif.ReturnValue;
               <br/>
               return(x);
               <br/>
               }
               <br/>
               If &lt;python:var&gt;runif&lt;/python:var&gt; was a global variable that was a reference to the S function, we would get ourselves into trouble. We would set the desired sample size in the S object. Then we call the Python function &lt;python:func&gt;getUniform&lt;/python:func&gt; recursively to generate the maximum value for this call. That second call, of course, resets the sample size to 1 in its call. As a result, the original call to &lt;python:func&gt;getUniform&lt;/python:func&gt; will generate only a single random value, not n values. Obviously, the approach to get around this is to have each call to &lt;python:func&gt;getUniform&lt;/python:func&gt; create its own instance of the runif COM object. But we had better remember to do this or we will see strange results. And of course, if we could call the runif’s Run with arguments in the call, this would avoid the “state” problem altogether. Of course, there would be other issues in compiled languages, but that is a different issue.
              </p>
              <p>
               Our approach
              </p>
              <p>
               As we have hinted earlier in this document, we recommend and have implemented a different approach to the ones described above. And ours is sufficiently flexible that one could implement both approaches above using our mechanism and some simple S code. Rather than exposing the S interpreter and having clients send S commands or exposing a function object that provides an invocation mechansism that involves setting state, we offer a mechanism that allows users to expose regular COM objects (i.e. with methods and properties) that are implemented in the S language. It handles arbitrary values both in the arguments and return values and is customizable in how it dispatches method invocations locally at the S-level. Additionally, providing S-level COM objects allows us to easily register for COM events, e.g. for Active X controls.
               <br/>
               The RDCOMServer package provides this mechanism and can be coupled with the RDCOMClient, SWinRegistry and SWinTypeLibs to give a comprehensive S-language interface to COM that is bidirectional and overcomes many of the limitations with the other approaches. It provides a rich, structured programming approach to distributed computing on Windows. A very similar CORBA interface is also possible which will hide the differences between the Unix and Windows details.
               <br/>
               ——————————————–
               <br/>
               Calling Visual Basic DLLs from R
               <br/>
               20/12/2004
               <br/>
               I want to test a series of growth models that are part of a DLL(Dynamic Link Library) written in Visual Basic. Although I could write several pieces of code in VB to test the library, I will try to access it from R. In this way I can run simulations and then process the results from within a statistical package.
              </p>
              <p>
               I obtained the RDCOM client and the SWinTypeLibs facilities from the Omega Hat Project for Statistical Computing. If you are running R 2.0 you should get the latest compilations from here (RDCOMClient_0.8-1.zip, 11-Oct-2004, 12:08, 433K and SWinTypeLibs_0.2-1.zip, 11-Oct-2004, 12:09, 147K).
              </p>
              <p>
               It is possible to learn about the classes, methods, parameters and return types of a COM server using the SWinTypeLibs library. Once we have learn about the server, we can access it using the RDCOMClient (this is explained in this presentation in PDF format, 50KB). For example:
              </p>
              <p>
               library(RDCOMClient)
               <br/>
               ie = COMCreate(“InternetExplorer.application”)
               <br/>
               ie[[“Visible”]] &lt;- TRUE\
               <br/>
               ie$Navigate2(“http://www.uncronopio.org/quantum/”)
               <br/>
               will load the library, connect to Internet Explorer, display the window and point the browser to Quantum Forest. An example using Excel would be:
              </p>
              <p>
               exc &lt;- COMCreate(“Excel.Application”)
               <br/>
               exc[[“Visible”]] &lt;- TRUE\
               <br/>
               books &lt;- exc[[“Workbooks”]]
               <br/>
               books$Add()
               <br/>
               actsheet &lt;- books[[1]][[“ActiveSheet”]]
               <br/>
               myrange &lt;- actsheet$Range(“A1:C10”)
               <br/>
               myrange[[“Value”]] &lt;- asCOMArray(matrix(rnorm(30, 10, 3)))
               <br/>
               This will connect to Excel, show the program, get a list of workbooks, add one, get which sheet is active, define a range and fill it with N(0,1) random numbers.
              </p>
              <p>
               I continue exploring the package to see if I can connect to my own DLL.
              </p>
              <p>
               Filed in programming, software, statistics
               <br/>
               There is 1 comment in this article:
               <br/>
               12/01/2008Quantum Forest » Blog Archive » Calling Visual Basic DLLs from R, part 2 say:
               <br/>
               […] Calling Visual Basic DLLs from R Resucitating Quantum Forest […]
               <br/>
               ———————————————–
               <br/>
               Calling Visual Basic DLLs from R, part 2
               <br/>
               21/12/2004
               <br/>
               After yesterday’s experience calling other software from R, I continued working to connect to my DLL. I first registered my DLL as a COM server in windows typing in the command line:
              </p>
              <p>
               regsvr32 c:\data\rconnect\growthmod.dll
               <br/>
               Then I had a look at my DLL using the SWinTypeLibs library, typing in R:
              </p>
              <p>
               library(SWinTypeLibs)
               <br/>
               wood &lt;- LoadTypeLib(“c:\data\rconnect\growthmodels.dll”)
               <br/>
               getTypeLibTypes(wood)
               <br/>
               DLLFuncs &lt;- getFuncs(wood[[1]])
               <br/>
               DLLElements &lt;- getElements(wood[[1]])
               <br/>
               The command getTypeLibTypes(wood) showed that the DLL contained _cPlantationModels (of type dispatch) and cPlantationModels (of type coclass). That is why I then continued working with wood[[1]], of type dispatch.
              </p>
              <p>
               After that I needed help from Tim. He had compiled the DLL leaving the class module cPlantationModels with an instancing of type 5 (multiUse), making it available for outside users. Connecting to the library was relatively straightforward with Tim’s help:
              </p>
              <p>
               library(RDCOMClient)
               <br/>
               growthmod &lt;- COMCreate(“growthmodels.cPlantationModels”)
               <br/>
               growthmod$ModelCreate(30,11,8,4,0,25,5,5,1000,0,1,2,0,1)
               <br/>
               standvol &lt;- growthmod$TreeValue(20)
               <br/>
               growthmod$ModelDestroy()
               <br/>
               This code loaded the RDCOM client library, created a connection to the DLL, instantiated a growth model with starting values, evaluated the model and destroyed the instantiation. Now we are ready to start testing the models from inside R.
              </p>
              <p>
               Filed in programming, software, statistics
               <br/>
               ———————————————-
               <br/>
               Calling R from Visual Basic
               <br/>
               4/02/2005
               <br/>
               Checking the server logs I have discovered that many people that arrive at my posts on calling VB from R are, in fact, looking for the reverse. I have never done any programming calling R from VB; however, while I was looking for COM clients for R I also found information on COM servers. OmegaHat lists RDCOMServer as a package that exports S (or R) objects as COM objects in Windows. It provides examples on using VB, Python and Perl to call R code.
              </p>
              <p>
               Another option is Thomas Baier’s R(D)COM Server, which is provided with examples in the same languages used by RDCOM Server.
              </p>
              <p>
               Filed in programming, statistics
               <br/>
               ————————————————-
              </p>
             </div>
             <!-- .bbp-reply-content -->
            </div>
            <!-- .reply -->
            <div class="bbp-reply-header" id="post-314041">
             <div class="bbp-meta">
              <span class="bbp-reply-post-date">
               2011年2月1日 上午2:48
              </span>
              <a class="bbp-reply-permalink" href="http://cos.name/cn/topic/103438/#post-314041">
               5 楼
              </a>
              <span class="bbp-admin-links">
              </span>
             </div>
             <!-- .bbp-meta -->
            </div>
            <!-- #post-314041 -->
            <div class="odd bbp-parent-forum-999 bbp-parent-topic-103438 bbp-reply-position-5 user-id-368205 post-314041 reply type-reply status-publish hentry">
             <div class="bbp-reply-author">
              <a class="bbp-author-avatar" href="http://cos.name/cn/profile/368205/" rel="nofollow" title="查看lincpa的档案">
               <img src="http://sdn.geekzu.org/avatar/498a47a5dba4347e539ca84572533720?s=80&amp;d=monsterid&amp;r=g"/>
              </a>
              <br/>
              <a class="bbp-author-name" href="http://cos.name/cn/profile/368205/" rel="nofollow" title="查看lincpa的档案">
               lincpa
              </a>
              <br/>
              <div class="bbp-author-role">
               普通会员
              </div>
             </div>
             <!-- .bbp-reply-author -->
             <div class="bbp-reply-content">
              <p>
               using r(d)com and rcom in .net applications
              </p>
              <p>
               R(D)COM .NET Wrapper
               <br/>
               by Igor Velikorossov of Insurance Australia Group, ©2004-2007.
              </p>
              <p>
               An interaction between R and .NET is made possible by R(D)COM and the following article will discuss the implementation of managed wrapper for R(D)COM and IStatConnectorCharacterDevice.
              </p>
              <p>
               Adding references
               <br/>
               Character Device
               <br/>
               Manager wrapper
               <br/>
               Basic wrapper
               <br/>
               Extending the wrapper with async calls
               <br/>
               Using the wrapper
              </p>
              <p>
               [ Downaload the demo project ]
              </p>
              <p>
               Step 1: Adding references
               <br/>
               First of all you need to include references to
              </p>
              <p>
               StatConnectorCommon 1.1 Type Library (StatConnectorSrv.tlb),
               <br/>
               StatConnectorSrv 1.1 Type Library (StatConnLib.tlb)
               <br/>
               both of these you should find at the COM tab when adding project’s references. The tlb’s are normally located at C:\Program Files\R\(D)COM Server\tlb
              </p>
              <p>
               Step 2: Character Device
               <br/>
               You need to implement IStatConnectorCharacterDevice interface to be able to capture output from R.
              </p>
              <p>
               The interface is pretty simple and defines only 3 methods.
              </p>
              <p>
               /// &lt;summary&gt;
               <br/>
               /// Managed wrapper for &lt;see cref=”IStatConnectorCharacterDevice”/&gt; interface.
               <br/>
               /// &lt;/summary&gt;
               <br/>
               public class CharacterDevice : IStatConnectorCharacterDevice, IDisposable
               <br/>
               {
               <br/>
               void IStatConnectorCharacterDevice.Clear()
               <br/>
               {
               <br/>
               }
              </p>
              <p>
               void IStatConnectorCharacterDevice.WriteString(string bstrLine)
               <br/>
               {
               <br/>
               }
              </p>
              <p>
               void IStatConnectorCharacterDevice.WriteStringLevel(string bstrLine, int lLevel)
               <br/>
               {
               <br/>
               }
               <br/>
               }The current implementation of the character device is based on RichTextBox control, and provides ability to color-code and indent output. For more details on implmentation please refer to CharacterDevice.cs.
              </p>
              <p>
               Step 3: Manager wrapper
               <br/>
               Now we are ready to implement the actual R(D)COM wrapper.
              </p>
              <p>
               Basic wrapper
               <br/>
               The proposed skeleton for the wrapper will look similar to the following:
              </p>
              <p>
               /// &lt;summary&gt;
               <br/>
               /// Managed R(D)Com wrapper.
               <br/>
               /// &lt;/summary&gt;
               <br/>
               public class Rcom : IDisposable
               <br/>
               {
               <br/>
               private		StatConnector		rsrv		= null;
               <br/>
               private		CharacterDevice	chardev		= new CharacterDevice();
              </p>
              <p>
               #region public Rcom()
               <br/>
               /// &lt;summary&gt;
               <br/>
               /// Initializes a new instance of the &lt;see cref=”Rcom”/&gt; class.
               <br/>
               /// &lt;/summary&gt;
               <br/>
               public Rcom()
               <br/>
               {
               <br/>
               this.chardev.DefaultColor	= Color.DarkGreen;
               <br/>
               this.chardev.DefaultIndent	= 30;
              </p>
              <p>
               this.rsrv = new StatConnectorClass();
               <br/>
               this.rsrv.Init(“R”);
               <br/>
               this.chardev.WriteString(“R initialised\r\n\r\n”, Color.Navy);
              </p>
              <p>
               this.rsrv.SetCharacterOutputDevice(this.chardev);
               <br/>
               }
               <br/>
               #endregion // public Rcom()
              </p>
              <p>
               }It is important to remember that we need to implement IDisposable interface to ensure that all unmanaged resources are released when the wrapper is no longer used and/or exists:
              </p>
              <p>
               protected virtual void Dispose(bool disposing)
               <br/>
               {
               <br/>
               // Check to see if Dispose has already been called.
               <br/>
               if (!this.disposed)
               <br/>
               {
               <br/>
               this.disposed = true;
              </p>
              <p>
               // If disposing equals true, dispose all managed
               <br/>
               // and unmanaged resources.
               <br/>
               if (disposing)
               <br/>
               {
               <br/>
               // Dispose managed resources.
               <br/>
               if (this.chardev != null)
               <br/>
               {
               <br/>
               this.chardev.Dispose();
               <br/>
               this.chardev = null;
               <br/>
               }
               <br/>
               }
              </p>
              <p>
               // Release unmanaged resources. If disposing is false,
               <br/>
               // only the following code is executed.
               <br/>
               if (this.rsrv != null)
               <br/>
               {
               <br/>
               this.rsrv.Close();
               <br/>
               Marshal.ReleaseComObject(this.rsrv);
               <br/>
               this.rsrv = null;
               <br/>
               }
               <br/>
               }
               <br/>
               }Extending the wrapper with async calls
               <br/>
               It is quite likely that some of operations may take a while to compute and it may be desirable not to lock the application until all of the computations are finished.
              </p>
              <p>
               To do this let’s allow calls to R be made in either sync or async modes:
              </p>
              <p>
               #region public JobStatus Submit(bool async)
               <br/>
               /// &lt;summary&gt;
               <br/>
               /// Submits the job for execution.
               <br/>
               /// &lt;/summary&gt;
               <br/>
               /// &lt;param name=”async”&gt;&lt;see langword=”true”/&gt; to run job in asynchronous mode;
               <br/>
               /// &lt;see langword=”false”/&gt; otherwise.&lt;/param&gt;
               <br/>
               /// &lt;returns&gt;Job state.&lt;/returns&gt;
               <br/>
               public JobStatus Submit(bool async)
               <br/>
               {
               <br/>
               if (this.rsrv == null)
               <br/>
               return JobStatus.Unknown;
              </p>
              <p>
               this.executionResult	= JobStatus.Unknown;
               <br/>
               this.running		= true;
              </p>
              <p>
               if (async)
               <br/>
               {
               <br/>
               // you can implement this call if desired
               <br/>
               //this.OnSubmitting();
              </p>
              <p>
               ThreadStart start = new ThreadStart(this.Execute);
               <br/>
               Thread thread = new Thread(start);
               <br/>
               thread.IsBackground = true;
               <br/>
               thread.Start();
               <br/>
               }
               <br/>
               else
               <br/>
               {
               <br/>
               this.Execute();
               <br/>
               }
              </p>
              <p>
               return this.executionResult;
               <br/>
               }
               <br/>
               #endregion // public JobStatus Submit(bool async)
              </p>
              <p>
               #region private void Execute()
               <br/>
               private void Execute()
               <br/>
               {
               <br/>
               lock (this.codeLines)
               <br/>
               {
               <br/>
               string line = string.Empty;
               <br/>
               try
               <br/>
               {
               <br/>
               this.chardev.StartCapture();
              </p>
              <p>
               // processing the code lines
              </p>
              <p>
               this.executionResult = JobStatus.Success;
               <br/>
               }
               <br/>
               catch (Exception ex)
               <br/>
               {
               <br/>
               this.chardev.WriteString(“\r\n&gt; ” + line + “\r\n”, Color.Red);
               <br/>
               this.chardev.WriteString(ex.ToString(), Color.Red);
              </p>
              <p>
               this.executionResult = JobStatus.Error;
               <br/>
               }
               <br/>
               finally
               <br/>
               {
               <br/>
               this.chardev.EndCapture();
               <br/>
               this.OnFinished(new FinishedEventArgs(this.executionResult, this.chardev.GetCapture(DataFormat.Rtf)));
               <br/>
               }
               <br/>
               }
               <br/>
               }
               <br/>
               #endregion // private void Execute()For more details on implmentation please refer to Rcom.cs.
              </p>
              <p>
               Step 4: Using the wrapper
               <br/>
               Using the wrapper is pretty much straight forward:
              </p>
              <p>
               try
               <br/>
               {
               <br/>
               // create teh R server
               <br/>
               this.rcom = new Rcom();
               <br/>
               // wire events
               <br/>
               this.rcom.LineEvaluated 	+= new LineEvaluatedHandler(rcom_LineEvaluated);
               <br/>
               this.rcom.Finished		+= new FinishedEventHandler(rcom_Finished);
              </p>
              <p>
               #region R code
               <br/>
               // R code
               <br/>
               this.rcom.CodeLines.AddRange(false, new string[] {
               <br/>
               “some_r_code_no_return;”,
               <br/>
               “more_of_r_code_no_return;”,
               <br/>
               });
               <br/>
               this.rcom.CodeLines.Add(“some_r_code_returning_value();”, true);
               <br/>
               this.rcom.CodeLines.AddRange(false, new string[] {
               <br/>
               // open bmp device
               <br/>
               “bmp(file=\”c:/pic.bmp\”, width=100, height=100);”,
               <br/>
               // plot
               <br/>
               “par(col=3);”,
               <br/>
               “plot(some_value, some_function(value));”,
               <br/>
               // save
               <br/>
               “dev.off();”,
               <br/>
               });
               <br/>
               }
               <br/>
               #endregion // R code
              </p>
              <p>
               // execute the code
               <br/>
               this.rcom.Submit(true);
               <br/>
               }
               <br/>
               catch (Exception ex)
               <br/>
               {
               <br/>
               MessageBox.Show(this,
               <br/>
               ex.ToString(),
               <br/>
               “R call failed”,
               <br/>
               MessageBoxButtons.OK,
               <br/>
               MessageBoxIcon.Error);
               <br/>
               }
              </p>
             </div>
             <!-- .bbp-reply-content -->
            </div>
            <!-- .reply -->
            <div class="bbp-reply-header" id="post-314043">
             <div class="bbp-meta">
              <span class="bbp-reply-post-date">
               2011年2月1日 上午2:57
              </span>
              <a class="bbp-reply-permalink" href="http://cos.name/cn/topic/103438/#post-314043">
               6 楼
              </a>
              <span class="bbp-admin-links">
              </span>
             </div>
             <!-- .bbp-meta -->
            </div>
            <!-- #post-314043 -->
            <div class="even bbp-parent-forum-999 bbp-parent-topic-103438 bbp-reply-position-6 user-id-368205 post-314043 reply type-reply status-publish hentry">
             <div class="bbp-reply-author">
              <a class="bbp-author-avatar" href="http://cos.name/cn/profile/368205/" rel="nofollow" title="查看lincpa的档案">
               <img src="http://sdn.geekzu.org/avatar/498a47a5dba4347e539ca84572533720?s=80&amp;d=monsterid&amp;r=g"/>
              </a>
              <br/>
              <a class="bbp-author-name" href="http://cos.name/cn/profile/368205/" rel="nofollow" title="查看lincpa的档案">
               lincpa
              </a>
              <br/>
              <div class="bbp-author-role">
               普通会员
              </div>
             </div>
             <!-- .bbp-reply-author -->
             <div class="bbp-reply-content">
              <p>
               重要参考1：
               <br/>
               <a href="http://learnserver.csd.univie.ac.at/rcomwiki/doku.php?id=wiki:user_2006_tutorial_on_r_d_com_rexcel_and_rcom" rel="nofollow">
                http://learnserver.csd.univie.ac.at/rcomwiki/doku.php?id=wiki:user_2006_tutorial_on_r_d_com_rexcel_and_rcom
               </a>
               <br/>
               重要参考2：
               <br/>
               <a href="http://sunsite.univie.ac.at/rcom/" rel="nofollow">
                http://sunsite.univie.ac.at/rcom/
               </a>
              </p>
             </div>
             <!-- .bbp-reply-content -->
            </div>
            <!-- .reply -->
            <div class="bbp-reply-header" id="post-314046">
             <div class="bbp-meta">
              <span class="bbp-reply-post-date">
               2011年2月1日 上午3:33
              </span>
              <a class="bbp-reply-permalink" href="http://cos.name/cn/topic/103438/#post-314046">
               7 楼
              </a>
              <span class="bbp-admin-links">
              </span>
             </div>
             <!-- .bbp-meta -->
            </div>
            <!-- #post-314046 -->
            <div class="odd bbp-parent-forum-999 bbp-parent-topic-103438 bbp-reply-position-7 user-id-368205 post-314046 reply type-reply status-publish hentry">
             <div class="bbp-reply-author">
              <a class="bbp-author-avatar" href="http://cos.name/cn/profile/368205/" rel="nofollow" title="查看lincpa的档案">
               <img src="http://sdn.geekzu.org/avatar/498a47a5dba4347e539ca84572533720?s=80&amp;d=monsterid&amp;r=g"/>
              </a>
              <br/>
              <a class="bbp-author-name" href="http://cos.name/cn/profile/368205/" rel="nofollow" title="查看lincpa的档案">
               lincpa
              </a>
              <br/>
              <div class="bbp-author-role">
               普通会员
              </div>
             </div>
             <!-- .bbp-reply-author -->
             <div class="bbp-reply-content">
              <p>
               C#调用R
               <br/>
               Posted in 2010/07/28 ¬ 12:00h.lijian没有评论 » 176 views
               <br/>
               C#可以很快捷地编程和实现界面，和R结合，能够很快地完成一个应用工具，本文简单介绍如何在C#中调用R。
              </p>
              <p>
               首先要在电脑中安装好Visual Studio（我测试的环境是VS2005）和R，目前比较成熟的方法是通过COM连接。那么就需要安装一个调用R的COM服务器。如果之前在电脑上安装过RExcel的话，那么电脑中已经装好了一个statconnDCOM。如果没有的话，需要到CRAN上下载一个R-(D)COM Interface，通过CRAN的主页，在Software栏目的Other里，目前的版本是R_Scilab_DCOM3.0-1B5.exe。
              </p>
              <p>
               装好后需要在R中安装rscproxy包（如果装过RExcel也会自动装好），将%R_HOME%\library\rscproxy\libs添入环境变量path。在开始菜单会看到一个DCOM的目录，点开Server 01 – Basic Test，进行测试，第一个按钮是“Start R”，测试通过就说明安装成功了。第二个按钮“Start SciLab”可能不成功，不过不影响我们使用R，它是另一个统计分析的类库。
              </p>
              <p>
               此时在VS中新建一个C#工程进行测试。在引用中进行添加，找到COM中的RServerManager.exe、StatConnectorClnt.dll、StatConnectorSrv.exe添加进去。我们新建一个Form，命名为Form1，然后添加一个button1和一个label1。在button1中定义button1_Click事件，写下如下代码：
              </p>
              <p>
               Form1.csint n = 86400;
               <br/>
               StatConnector conR = new STATCONNECTORSRVLib.StatConnectorClass();
               <br/>
               conR.Init(“R”);
               <br/>
               conR.SetSymbol(“M2″, n);
               <br/>
               conR.EvaluateNoReturn(“library(timeDate)”);
               <br/>
               label1.Text = conR.Evaluate(“dayOfWeek(timeDate(Sys.time()+M2))[[1]]”).ToString();
               <br/>
               运行后点击button1，可以发现label1的位置可以显示明天是星期几。该例子测试了传参数、调R包、执行语句、返回值。
              </p>
             </div>
             <!-- .bbp-reply-content -->
            </div>
            <!-- .reply -->
           </li>
           <!-- .bbp-body -->
           <li class="bbp-footer">
            <div class="bbp-reply-author">
             作者
            </div>
            <div class="bbp-reply-content">
             帖子
            </div>
            <!-- .bbp-reply-content -->
           </li>
           <!-- .bbp-footer -->
          </ul>
          <!-- #topic-103438-replies -->
          <div class="bbp-pagination">
           <div class="bbp-pagination-count">
            查看 7 个帖子 - 1 到 7（总计 7 个）
           </div>
           <div class="bbp-pagination-links">
           </div>
          </div>
          <div class="bbp-no-reply" id="no-reply-103438">
           <div class="bbp-template-notice">
            <p>
             您必须先登录才能回复该主题。
            </p>
           </div>
          </div>
         </div>
        </div>
        <!-- .entry-content -->
        <footer class="entry-meta">
        </footer>
        <!-- .entry-meta -->
       </article>
       <!-- #post -->
       <div class="comments-area" id="comments">
       </div>
       <!-- #comments -->
      </div>
      <!-- #content -->
     </div>
     <!-- #primary -->
     <div class="sidebar-container" id="tertiary" role="complementary">
      <div class="sidebar-inner">
       <div class="widget-area">
        <aside class="widget bbp_widget_login" id="bbp_login_widget-2">
         <h3 class="widget-title">
          登录
         </h3>
         <form action="http://cos.name/cn/wp-login.php" class="bbp-login-form" method="post">
          <fieldset>
           <legend>
            登录
           </legend>
           <div class="bbp-username">
            <label for="user_login">
             用户名:
            </label>
           </div>
           <div class="bbp-password">
            <label for="user_pass">
             密码:
            </label>
           </div>
           <div class="bbp-remember-me">
            <label for="rememberme">
             记住用户名
            </label>
           </div>
           <div class="bbp-submit-wrapper">
            <button class="button submit user-submit" id="user-submit" name="user-submit" tabindex="104" type="submit">
             登录
            </button>
           </div>
           <div class="bbp-login-links">
            <a class="bbp-register-link" href="http://cos.name/cn/wp-login.php?action=register" title="注册">
             注册
            </a>
            <a class="bbp-lostpass-link" href="http://cos.name/cn/wp-login.php?action=lostpassword" title="忘记密码">
             忘记密码
            </a>
           </div>
          </fieldset>
         </form>
        </aside>
        <aside class="widget widget_text" id="text-7">
         <h3 class="widget-title">
          搜索
         </h3>
         <div class="textwidget">
          <form action="http://www.google.com/search" id="bbp-search-form" method="get" onsubmit="Gsitesearch(this)" role="search">
           <div>
           </div>
          </form>
          <form id="bbp-search-form-baidu" onsubmit="g(this)" role="search">
           <div>
           </div>
          </form>
         </div>
        </aside>
        <aside class="widget widget_text" id="text-2">
         <h3 class="widget-title">
          新鲜事
         </h3>
         <div class="textwidget">
          <ul>
           <li>
            <a href="http://cos.name/cn/topics/">
             最新帖子
            </a>
           </li>
           <li>
            <a href="http://cos.name/cn/view/popular/">
             最热门主题
            </a>
           </li>
           <li>
            <a href="http://cos.name/cn/view/no-replies/">
             消灭零回复
            </a>
           </li>
          </ul>
         </div>
        </aside>
        <aside class="widget widget_text" id="text-3">
         <h3 class="widget-title">
          RSS订阅
         </h3>
         <div class="textwidget">
          <ul>
           <li>
            <img src="http://cos.name/wp-includes/images/rss.png"/>
            <a href="http://cos.name/cn/topics/feed/">
             所有主题
            </a>
           </li>
           <li>
            <img src="http://cos.name/wp-includes/images/rss.png"/>
            <a href="http://cos.name/cn/forums/feed/">
             所有帖子
            </a>
           </li>
          </ul>
         </div>
        </aside>
       </div>
       <!-- .widget-area -->
      </div>
      <!-- .sidebar-inner -->
     </div>
     <!-- #tertiary -->
    </div>
    <!-- #main -->
    <footer class="site-footer" id="colophon" role="contentinfo">
     <div class="site-info">
      版权所有 © 2014 统计之都 | 由
      <a href="http://wordpress.org/">
       WordPress
      </a>
      构建 | 主题修改自
      <a href="http://wordpress.org/themes/twentythirteen">
       Twenty Thirteen
      </a>
     </div>
     <!-- .site-info -->
    </footer>
    <!-- #colophon -->
   </div>
   <!-- #page -->
  </div>
 </body>
</html>